/*
******************
* author: 马丰彦
* date: 2019
* function: aes加密+base64加密解密
******************
*/

const CryptoJS = require('crypto-js')
import urlencode from '@/utils/urlencode'
import urldecode from '@/utils/urldecode'
// 加密串
const key = CryptoJS.enc.Utf8.parse('rockrollformusic')
const iv = CryptoJS.enc.Utf8.parse('rockrollformusic')
// 解密方法
function Decrypt(word) {
  const base64Data = urldecode(word)
  const hexParse = CryptoJS.enc.Base64.parse(base64Data)
  const hexData = CryptoJS.enc.Hex.stringify(hexParse)
  const encryptedHexStr = CryptoJS.enc.Hex.parse(hexData)
  const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
  const decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr.toString()
}

// 加密方法
// 默认 hex 16进制 已转为base64格式，并进行encode转码
function Encrypt(word) {
  var jsonData = JSON.stringify(word)
  const srcs = CryptoJS.enc.Utf8.parse(jsonData)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding })
  var hexData = encrypted.ciphertext.toString().toUpperCase()
  // 开始base64转码
  var hexParse = CryptoJS.enc.Hex.parse(hexData)
  var base64Data = CryptoJS.enc.Base64.stringify(hexParse)
  // encode转码
  var enBase64Data = urlencode(base64Data)
  return enBase64Data
}

export default {
  Decrypt,
  Encrypt
}

